﻿using CKS2320.Common.Model;
using CKS2320.Common.Utils;
using CKS2320.Domain.DBEntity;
using CKS2320.Repository.Interface;
using MathNet.Numerics.Statistics.Mcmc;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace CKS2320.Repository
{
    public class ThicknessDetectionRepository : IThicknessDetectionRepository
    {
        public DBContext _dbCotext;
        public ThicknessDetectionRepository(DBContext dbCotext)
        {
            _dbCotext = dbCotext;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="tdEntity"></param>
        /// <param name="detailList"></param>
        /// <returns></returns>
        public ResultReturn Add(Thicknessdetection tdEntity, List<Detectiondetail> detailList, Op30coredata op30CoreData)
        {

            var entity = _dbCotext.Thicknessdetections.Add(tdEntity);
            if (entity != null)
            {
                _dbCotext.Detectiondetails.AddRange(detailList);
            }

            var dataStatus = _dbCotext.Datastatuses.FirstOrDefault(p => p.ContentStatus != 1);
            if (dataStatus != null)
            {
                dataStatus.ContentStatus = 1;
                _dbCotext.Datastatuses.Update(dataStatus);
            }
            _dbCotext.Op30coreDatas.Add(op30CoreData);
            _dbCotext.SaveChanges();
            return MessageInfoUtils.Success(tdEntity.Id);


        }

        /// <summary>
        /// 查找今天的性能率
        /// </summary>
        /// <returns></returns>
        public ResultReturn SelectPerformanceRecord()
        {
            try
            {
                List<PerformanceRecord> instance = new List<PerformanceRecord>();
                DateTime today = DateTime.Today;
                // 构造当天的开始时间（0点）
                DateTime startOfDay = new DateTime(today.Year, today.Month, today.Day, 0, 0, 0);
                // 构造当天的结束时间（24点）
                DateTime endOfDay = new DateTime(today.Year, today.Month, today.Day, 23, 59, 59);
                instance = _dbCotext.PerformanceRecords.Where(p => p.CreatedTime >= startOfDay && p.CreatedTime <= endOfDay).ToList();
                if (instance != null && instance.Count > 0)
                {
                    PerformanceRecord ins = instance.LastOrDefault();
                    if (ins.StopTime < 0)
                    {
                        ins.StopTime = 0;
                    }
                    if (ins.WaitingTime < 0)
                    {
                        ins.WaitingTime = 0;
                    }
                    if (ins.FaultTime < 0)
                    {
                        ins.FaultTime = 0;
                    }
                    return MessageInfoUtils.Success(ins);
                }
            }
            catch (Exception ex)
            {
                return MessageInfoUtils.Fail(ex.ToString());
            }
            return MessageInfoUtils.Fail();
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <returns></returns>
        public OeeConfig OeeConfigLoad()
        {
            string filePath = "OeeConfig.json";
            string text = File.ReadAllText(filePath);
            return JsonConvert.DeserializeObject<OeeConfig>(text);
        }

        /// <summary>
        /// 添加性能率记录
        /// </summary>
        /// <param name="record">记录</param>
        /// <returns></returns>
        public ResultReturn AddPerformanceRecord(PerformanceRecord record)
        {
            try
            {
                OeeConfig oeeconfigInstance = OeeConfigLoad();
                float? productionPlan = 0;
                float? rhythm = 0;
                float? totalcountplan = 0;
                if (oeeconfigInstance != null)
                {
                    productionPlan = oeeconfigInstance.ProductionPlanTime;
                    rhythm = oeeconfigInstance.Rhythm;
                    totalcountplan = oeeconfigInstance.TotalCountPlan;
                }
                else
                {
                    OeeConfig oeeins = new OeeConfig();
                    productionPlan = oeeins.ProductionPlanTime;
                    rhythm = oeeins.Rhythm;
                    totalcountplan = oeeins.TotalCountPlan;
                }
                if (record != null)
                {
                    List<Thicknessdetection> list = new List<Thicknessdetection>();
                    List<PerformanceRecord> pList = new List<PerformanceRecord>();//接收已存在于数据库的数据
                    //时间开动率
                    float? result = 0;
                    //性能开动率
                    float? Efficiency = 0;
                    //良率
                    float ProductYield = 0;
                    //完工率
                    float? completeRate = 0;
                    // 获取当前日期
                    DateTime today = DateTime.Today;

                    // 构造当天的开始时间（0点）
                    DateTime startOfDay = new DateTime(today.Year, today.Month, today.Day, 0, 0, 0);
                    // 构造当天的结束时间（24点）
                    DateTime endOfDay = new DateTime(today.Year, today.Month, today.Day, 23, 59, 59);

                    pList = _dbCotext.PerformanceRecords.Where(p => p.CreatedTime >= startOfDay && p.CreatedTime <= endOfDay).ToList();
                    if (pList.Count > 0)
                    {
                        //foreach (var item in pList)
                        //{
                        //    record.TotalRunTime += item.TotalRunTime;
                        //    record.WaitingTime += item.WaitingTime;
                        //    record.StopTime += item.StopTime;
                        //    record.FaultTime += item.FaultTime;
                        //}
                        PerformanceRecord instance = pList.LastOrDefault();
                        record.TotalRunTime += instance.TotalRunTime;
                        record.WaitingTime += instance.WaitingTime;
                        record.StopTime += instance.StopTime;
                        record.FaultTime += instance.FaultTime;
                    }

                    list = _dbCotext.Thicknessdetections.Where(p => p.CreatedTime >= startOfDay && p.CreatedTime <= endOfDay).ToList();
                    //运行时间-停止时间=负荷时间
                    record.LoadTime = record.TotalRunTime - record.StopTime;
                    if (record.LoadTime > 0)
                    {
                        //运行时间-等待时间-故障时间=停机时间
                        record.DownTime = record.WaitingTime + record.FaultTime;

                        if ((record.LoadTime - record.DownTime) > 0)
                        {
                            //时间开动率=（负荷时间-停机时间）/负荷时间%
                            //result = (record.LoadTime - record.DownTime) / record.TotalRunTime;
                            result = (float)((/*800f*/productionPlan - record.DownTime) / productionPlan/*800f*/);
                            record.StartRate = (result * 100).Value.ToString("F1") + "%";
                        }
                        if (list.Count > 0)
                        {
                            //float? rhythm = 0.4f;
                            //（设计节拍*产量）/负荷时间 %
                            Efficiency = (rhythm * list.Count) / record.LoadTime;
                            record.Efficiency = (Efficiency * 100).Value.ToString("F1") + "%";
                        }
                    }
                    if (list.Count > 0)
                    {
                        float? NGCount = list.Where(p => p.FacadeCurvatureResult == false).ToList().Count;
                        ProductYield = (float)((list.Count - NGCount) / list.Count);
                        record.ProductYield = (ProductYield * 100).ToString("F1") + "%";
                        completeRate = (float)(list.Count / totalcountplan/*2000f*/);
                    }
                    //float? oee = result * Efficiency * ProductYield;
                    float? oee = result * ProductYield * completeRate;
                    record.OEE = (oee * 100).Value.ToString("F1") + "%";
                    record.CreatedTime = DateTime.Now;
                    record.ModifiedTime = DateTime.Now;
                    _dbCotext.PerformanceRecords.Add(record);
                    _dbCotext.SaveChanges();
                    return MessageInfoUtils.Success();
                }
            }
            catch (Exception ex)
            {

                return MessageInfoUtils.Fail(ex.ToString());
            }
            return MessageInfoUtils.Fail();

        }

        /// <summary>
        /// 根据partcode获取列表信息
        /// </summary>
        /// <param name="partCode"></param>
        /// <returns></returns>
        public IEnumerable<Thicknessdetection> GetByPartCode(string partCode)
        {
            return _dbCotext.Thicknessdetections.Where(p => p.PartCode == partCode).ToList();
        }
        /// <summary>
        /// 根据partcode获取列表信息
        /// </summary>
        /// <param name="partCode"></param>
        /// <returns></returns>
        public Thicknessdetection GetByID(Guid? parentid)
        {
            return _dbCotext.Thicknessdetections.FirstOrDefault(p => p.Id == parentid);
        }
        /// <summary>
        /// 基恩士激光扫描仪数据添加
        /// </summary>
        /// <param name="detailList"></param>
        /// <returns></returns>
        public ResultReturn KeyenceAdd(List<Detectiondetail> detailList)
        {
            _dbCotext.Detectiondetails.AddRange(detailList);
            _dbCotext.SaveChanges();
            return MessageInfoUtils.Success();
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public List<ThicknessDetectionModel> ExportQueryList(TotalReq req)
        {
            var filters = new List<Func<Thicknessdetection, bool>>();
            if (!string.IsNullOrEmpty(req.StartTime))
            {
                filters.Add(p => p.CreatedTime >= Convert.ToDateTime(req.StartTime));
            }
            if (!string.IsNullOrEmpty(req.EndTime))
            {
                filters.Add(p => p.CreatedTime <= Convert.ToDateTime(req.EndTime));
            }
            if (!string.IsNullOrEmpty(req.Status))
            {
                filters.Add(p => p.Result == (req.Status.ToLower() == "ok"));
            }
            List<Thicknessdetection> thicknessdetections = new();
            var query = _dbCotext.Thicknessdetections.Where(p => filters.All(filter => filter(p))).OrderByDescending(p => p.CreatedTime);
            if (req.page != null && req.size != null)
            {
                thicknessdetections = query.Skip((req.page.Value - 1) * req.size.Value).Take(req.size.Value).ToList();
            }
            else
            {
                thicknessdetections = query.ToList();
            }
            if (thicknessdetections != null && thicknessdetections.Any())
            {
                var qs = from a in thicknessdetections
                         join b in _dbCotext.Detectiondetails on a.Id equals b.ParentId
                         select new ThicknessDetectionModel
                         {
                             BackThicknessResult1 = a.BackThicknessResult1,
                             BackThicknessResult2 = a.BackThicknessResult2,
                             BackThicknessResult3 = a.BackThicknessResult3,
                             BackThicknessResult4 = a.BackThicknessResult4,
                             BackThicknessResult5 = a.BackThicknessResult5,
                             BackThicknessResult6 = a.BackThicknessResult6,
                             BackThicknessResult7 = a.BackThicknessResult7,
                             FrontThicknessResult1 = a.FrontThicknessResult1,
                             FrontThicknessResult2 = a.FrontThicknessResult2,
                             FrontThicknessResult3 = a.FrontThicknessResult3,
                             FrontThicknessResult4 = a.FrontThicknessResult4,
                             FrontThicknessResult5 = a.FrontThicknessResult5,
                             FrontThicknessResult6 = a.FrontThicknessResult6,
                             FrontThicknessResult7 = a.FrontThicknessResult7,
                             Crfront1WaveDistanceResult = a.Crfront1WaveDistanceResult,
                             Crfront64WaveDistanceResult = a.Crfront64WaveDistanceResult,
                             CrlargeEndDistanceResult = a.CrlargeEndDistanceResult,
                             CrsmallEndDistanceResult = a.CrsmallEndDistanceResult,
                             EndUpLoad = a.EndUpLoad,
                             FacadeCurvatureResult = a.FacadeCurvatureResult,
                             SmallEndDirectionInspectionResult = a.SmallEndDirectionInspectionResult,
                             StationCode = a.StationCode,
                             TotalLengthResult = a.TotalLengthResult,
                             _3dscannerEnd = a._3dscannerEnd,
                             _3dscannerResult1 = a._3dscannerResult,
                             _3dscannerStart = a._3dscannerStart,
                             Heart1 = a.Heart1,
                             Heart2 = a.Heart2,
                             StartUpLoad = a.StartUpLoad,
                             PartCode = a.PartCode,
                             Result = a.Result,
                             RunType = a.RunType,
                             detaillist = new List<DetectionDetail>()
                             {
                                 new DetectionDetail()
                                 {
                                     Id = b.Id, ParentId = b.ParentId,
                                     Description = b.Description,
                                     DetectedData = b.DetectedData,
                                     DetectedType = b.DetectedType
                                 }}
                         };

                return qs.ToList();
            }
            return new List<ThicknessDetectionModel>();
        }



        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public List<Detectiondetail> Export3DKeyenceList(TotalReq req)
        {
            //List<Detectiondetail> details = new();

            DateTime start = Convert.ToDateTime(req.StartTime + " 00:00:00");
            DateTime end = Convert.ToDateTime(req.EndTime + " 23:59:59");

            var details = _dbCotext.Detectiondetails.Where(p => p.CreatedTime >= start && p.CreatedTime <= end && (p.DetectedType.Contains("正面波直径") || p.DetectedType.Contains("正面波间距") || p.DetectedType.Contains("背面波直径") || p.DetectedType.Contains("背面波间距") || p.DetectedType.Contains("C基准"))).OrderByDescending(p => p.CreatedTime).ToList();
            return details;
        }
    }
}
